//
//  OAuthViewController.swift
//  Weobo
//
//  Created by 史亚洲 on 16/1/12.
//  Copyright © 2016年 itcast. All rights reserved.


import UIKit
import SVProgressHUD
import AFNetworking


class OAuthViewController: UIViewController {
    
    //属性的webView
    let webView = UIWebView()
    
    
    //MARK: 关闭页面
    @objc private func close() {
        //dismiss页面
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    //自动填充账号
    @objc private func defaultAccount() {
        let jsonString =  "document.getElementById('userId').value = '15896976173',document.getElementById('passwd').value = 'Asia199322'"
        webView.stringByEvaluatingJavaScriptFromString(jsonString)
        
        
        
    }
    
    
    override func loadView() {
        //将根视图 替换为 webView
        view = webView
        //设置代理
        webView.delegate = self
    }
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //文字渲染颜色
        //只正对当前的导航视图控制器有效
        //        navigationController?.navigationBar.tintColor = UIColor.orangeColor()
        
        //一经设置 全局有效
        //        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        print(view)
        //设置导航条
        setNavBar()
        
        //加载授权页面
        loadOAuthPage()
    }
    
    private func setNavBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAccount")
    }
    
    //MARK: 加载授权页面
    private func loadOAuthPage() {
        
        ////        let appKey = "2041132065"
        ////        let appSecret = "c2c4a981dda938c8bf2156e53391823c"
        ////        let redirectUri = "http://itcast.com"
        //
        ////        let urlString1 = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUri)"
        
        
        
        //1. 获取url
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        //可选的url
        let url = NSURL(string: urlString)!
        //获取request
        let request = NSURLRequest(URL: url)
        
        webView.loadRequest(request)
        
    }
    
    
}



//swift中 这样写  是将一类的协议方法  写在一起 更加好阅读 和 维护
//1.同一类的协议方法  就被放在一个扩展中
extension OAuthViewController: UIWebViewDelegate {
    //1.显示 用户等待指示器
    func webViewDidStartLoad(webView: UIWebView) {
        //显示
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //隐藏
        SVProgressHUD.dismiss()
    }
    
    
    //2.通常协议方法 返回值 为 bool类型  返回 yes 通常控件可以正常运行
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //截取code中的授权码code=fc5a01ce1ecd42d14cf6bb180b69c0c5
        //print(request.URL?.absoluteString)
        
        
        //看是否能获取url字符串,如果不能,直接不加载网页
        guard let urlString = request.URL?.absoluteString else  {
            
            
            return false
            
        }
        
        if urlString.containsString("code="){
            
            print(urlString)
            
            //获取url的参数
            guard let query = request.URL?.query else{
                
                return false
                
            }
            
            let codeStr = "code="
            
            //将query转换成NSString subString
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            
            print(code,query)
            
            //调用获取token的方法
            loadAccessToken(code)
            
            
            //不让页面跳转到回调页面
            return false
            
        }
        
        // print(request.URL)
        
        return true
    }
    
    private func loadAccessToken(code: String) {
        
        //请求token和用户信息
        UserAccountViewModel().loadAccessToken(code) { (isSuccess) -> () in
            
            //1.登录失败
            if !isSuccess {
                print("用户登录失败")
                SVProgressHUD.showErrorWithStatus("当前网络不稳定,请稍候再试")
                return
                
                
            }
            
            //2.一定登录成功
            SVProgressHUD.showInfoWithStatus("登录成功")
            
            //注意:dismiss的时候,HomeTableVC没有真正的释放掉
            //执行dismiss操作,对应的页不会被销毁

           self.dismissViewControllerAnimated(false, completion: { () -> Void in
            
            //发出通知,通知是同步的
            NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVC, object: "Welcome")
           
            
            print("come here")
           })
//            //切换根视图,不推荐这样写,使用通知比较好
//            UIApplication.sharedApplication().keyWindow?.rootViewController = WelcomeViewController()
          
            
        }
        
        
        
        
    }
    
}



